using System;
using System.Collections;
using UnityEngine;

namespace PKGames.AssetBundleSystem
{
	public class AssetBundleLoadRequest : IEnumerator
	{
		private bool _isDone;

		private string _assetBundleName = string.Empty;

		private AssetBundleLoader _downloader;

		private Action<float> _progressAction;

		public AssetBundle AssetBundle => _downloader.GetAssetBundle();

		public object Current => null;

		public AssetBundleLoadRequest(string assetBundleName, string url, Action<float> progressAction)
		{
			_assetBundleName = assetBundleName;
			_progressAction = progressAction;
			_downloader = new FileAssetBundleLoader(assetBundleName, url);
			try
			{
				_downloader.Start();
			}
			catch
			{
				_downloader = null;
			}
		}

		private bool IsDownloadFinished()
		{
			return _downloader == null || _downloader.IsDone();
		}

		public bool MoveNext()
		{
			return Update();
		}

		public void Reset()
		{
		}

		private bool Update()
		{
			if (IsDownloadFinished())
			{
				if (CheckError())
				{
					HandleError();
				}
				else
				{
					HandleSuccess();
				}
			}
			UpdateProgress();
			return !_isDone;
		}

		private bool CheckError()
		{
			return _downloader == null || !string.IsNullOrEmpty(_downloader.GetError()) || _downloader.GetAssetBundle() == null;
		}

		private void HandleSuccess()
		{
			Cleanup();
			_isDone = true;
		}

		private void HandleError()
		{
			string error = _downloader.GetError();
			if (!string.IsNullOrEmpty(error))
			{
				Cleanup();
				throw new AssetBundleNetworkException(error);
			}
			if (_downloader.GetAssetBundle() == null)
			{
				Cleanup();
				throw new AssetBundleNetworkException("Invalid Bundle: " + _assetBundleName);
			}
		}

		private void Cleanup()
		{
			if (_downloader != null)
			{
				_downloader.Cleanup();
			}
			_isDone = true;
		}

		private void UpdateProgress()
		{
			if (_downloader != null)
			{
				_progressAction.Fire(_downloader.GetProgress());
			}
			else
			{
				_progressAction.Fire(1f);
			}
		}
	}
}
